#!/bin/bash

# 设置工作目录
cd "$(dirname "$0")"

# 设置颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查端口是否被占用
check_port() {
    if lsof -i:8116 >/dev/null 2>&1; then
        echo -e "${RED}Port 8116 is already in use${NC}"
        echo -e "${YELLOW}Attempting to stop existing process...${NC}"
        ./stop.sh
        if [ $? -ne 0 ]; then
            echo -e "${RED}Failed to stop existing process${NC}"
            exit 1
        fi
    fi
}

echo -e "${YELLOW}Starting FastAPI server deployment...${NC}"

# 检查端口
check_port

# 检查并创建日志目录
if [ ! -d "./logs" ]; then
    echo -e "${YELLOW}Creating logs directory...${NC}"
    mkdir -p ./logs
fi

# 日志轮转：保留最近5个日志文件
echo -e "${YELLOW}Rotating logs...${NC}"
if [ -f "./logs/server.log" ]; then
    for i in {4..1}; do
        if [ -f "./logs/server.log.$i" ]; then
            mv "./logs/server.log.$i" "./logs/server.log.$((i+1))"
        fi
    done
    mv "./logs/server.log" "./logs/server.log.1"
fi

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo -e "${YELLOW}Creating virtual environment...${NC}"
    python -m venv venv
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to create virtual environment${NC}"
        exit 1
    fi
fi

# 激活虚拟环境
echo -e "${YELLOW}Activating virtual environment...${NC}"
source venv/bin/activate

# 安装/更新依赖
echo -e "${YELLOW}Installing/Updating dependencies...${NC}"
pip install -q -r requirements.txt

# 再次检查端口（以防在安装依赖期间被占用）
check_port

# 启动 FastAPI 服务器
echo -e "${YELLOW}Starting FastAPI server...${NC}"
nohup python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8116 > ./logs/server.log 2>&1 &

# 等待服务器启动
echo -e "${YELLOW}Waiting for server to start...${NC}"
max_attempts=30
attempt=1
while [ $attempt -le $max_attempts ]; do
    if lsof -i:8116 >/dev/null 2>&1; then
        echo -e "${GREEN}FastAPI server started successfully${NC}"
        echo -e "${GREEN}Logs available at ./logs/server.log${NC}"
        
        # 显示最新的日志内容
        echo -e "${YELLOW}Recent log entries:${NC}"
        tail -n 5 ./logs/server.log
        exit 0
    fi
    echo -n "."
    sleep 1
    attempt=$((attempt + 1))
done

echo -e "\n${RED}Failed to start FastAPI server after $max_attempts seconds${NC}"
echo -e "${RED}Check logs at ./logs/server.log for details${NC}"
tail -n 10 ./logs/server.log
exit 1 